package org.shoukaiseki.test.spring.springbootdemo.oss.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.shoukaiseki.aliyun.oss.config.AliyunOSSCoreProperties;
import org.shoukaiseki.test.spring.springbootdemo.oss.domain.ImgModel;
import org.shoukaiseki.test.spring.springbootdemo.oss.domain.StsInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

/** com.shoukaiseki.test.spring.springbootdemo.oss.controller.OssController 
 * <br>
 * @author shoukaiseki 
 * ブログ http://www.shoukaiseki.top/<br>
 * E-メール jiang28555@Gmail.com<br>
 * @date 2020-11-28 18:24:07<br>
 */
@Controller
@RequestMapping("/oss")
@Scope("session")
public class OssController {

    @Resource
    AliyunOSSCoreProperties aliyunOSSCoreProperties;

    private boolean firstAccess=true;

    /**
     * 用作key的序列自增
     */
    private int imgId=1;

    private Map<Integer, ImgModel> data;


    @RequestMapping("/list")
    @ResponseBody
    public Object imageList(){
        if(firstAccess){
            firstAccess=false;
            data=initImage();
        }

        return data.values();
    }

    @RequestMapping("/stsToken")
    @ResponseBody
    public Object stsToken( @RequestParam("fileName") String fileName ,@RequestParam("size")int size) throws ClientException {
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        String newFileName = uuid+fileName.substring(fileName.lastIndexOf("."));
        String ossFileName = newFileName;
        if(aliyunOSSCoreProperties.getPath()!=null){
            ossFileName=aliyunOSSCoreProperties.getPath()+"/"+newFileName;
        }
        StsInfo stsInfo=getStsInfo(ossFileName);
        stsInfo.setFileName(ossFileName);
        int key = imgId++;
        stsInfo.setWbDocmentId((long)key);

        String url = generateUrl(aliyunOSSCoreProperties.getEndpoint(), aliyunOSSCoreProperties.getBucketName(), ossFileName);
        stsInfo.setUrl(url);

        ImgModel imgModel = new ImgModel();
        imgModel.setWbDocmentId((long) key);
        imgModel.setUrl(url);
        imgModel.setName(fileName);
        imgModel.setSize(size);
        data.put(key, imgModel);


        return Map.of("code","0","data",stsInfo);
    }


    final Logger logger= LoggerFactory.getLogger(OssController.class);
    public StsInfo getStsInfo(String fileName) throws ClientException {

        if (logger.isDebugEnabled()) {
//            logger.debug("aliyunOSSCoreProperties="+ JSONObject.toJSONString(aliyunOSSCoreProperties));
//            logger.debug("aliyunOSSCoreProperties.getAccessKeyId()="+aliyunOSSCoreProperties.getAccessKeyId());
//            logger.debug("aliyunOSSCoreProperties.getSecretAccessKey()="+aliyunOSSCoreProperties.getSecretAccessKey());
//            logger.debug("111agt");
        }

        // 构造default profile（参数留空，无需添加region ID）
        IClientProfile profile = DefaultProfile.getProfile("", aliyunOSSCoreProperties.getAccessKeyId(), aliyunOSSCoreProperties.getSecretAccessKey());
        // 用profile构造client
        DefaultAcsClient client = new DefaultAcsClient(profile);
        AssumeRoleRequest request = new AssumeRoleRequest();


        String stsEndpoint=aliyunOSSCoreProperties.getSysEndpoint();
//        request.setActionName("sts:AssumeRole");
        request.setSysEndpoint(stsEndpoint);
        request.setSysMethod(MethodType.POST);
        request.setRoleArn(aliyunOSSCoreProperties.getRoleArn());
        request.setRoleSessionName(aliyunOSSCoreProperties.getRoleSessionName());
        request.setDurationSeconds(1500L);
        final AssumeRoleResponse response = client.getAcsResponse(request);


        StsInfo stsInfo = new StsInfo();


        AssumeRoleResponse.Credentials credentials = response.getCredentials();
        stsInfo.setAccessKeyId(credentials.getAccessKeyId());
        stsInfo.setAccessKeySecret(credentials.getAccessKeySecret());
        stsInfo.setBucket(aliyunOSSCoreProperties.getBucketName());
        stsInfo.setEndpoint(aliyunOSSCoreProperties.getEndpoint());
        stsInfo.setStsToken(credentials.getSecurityToken());



        return stsInfo;
    }
    /**
     * 生成oss访问URL
     * @param ossFilename
     * @return
     */
    public String generateUrl(String endpoint,String bucketName, String ossFilename) {
        StringBuilder sb=new StringBuilder();
        sb.append("https://");
        sb.append(bucketName);
        sb.append(".");
        sb.append(endpoint);
        sb.append("/");
        sb.append(ossFilename);
        return sb.toString();
    }


    @PostMapping("/deleteDocment")
    @ResponseBody
    public Map deleteDocment(Long wbDocmentId)  {
        int key = wbDocmentId.intValue();
        boolean b = data.containsKey(key);
        if(!b){
            //fileinput的判断是,返回值中存在error属性就算删除出错
            /**
             fnSuccess = function (data, textStatus, jqXHR) {1602行

             if (data.error) {
             */
            return Map.of("error","记录不存在");
        }
        data.remove(key);
        return Map.of("message","成功删除");
    }

    private Map<Integer, ImgModel> initImage() {
        //使用有序map
        data=new LinkedHashMap();
        String[] imgUrls={
                "https://dpic.tiankong.com/mz/f1/QJ6415651243.jpg"
                ,"https://dpic.tiankong.com/kp/b7/QJ6431332977.jpg"
                ,"https://dpic.tiankong.com/6u/d5/QJ6507206819.jpg"
                ,"https://dpic.tiankong.com/id/ud/QJ6515004618.jpg"
                ,"https://dpic.tiankong.com/6k/kp/QJ6580454947.jpg"
        };

        for (String imgUrl : imgUrls) {

            ImgModel imgModel = new ImgModel();
            int key = imgId++;
            imgModel.setWbDocmentId((long) key);
            imgModel.setUrl(imgUrl);
            imgModel.setName("图片"+imgId);
            imgModel.setSize(1024*60);
            data.put(key, imgModel);
        }

        return data;
    }



}
